package com.prd.service.impl;

import com.prd.config.LoginInterceptor;
import com.prd.constant.CacheKey;
import com.prd.enums.BizCodeEnum;
import com.prd.enums.SendCodeEnum;
import com.prd.enums.UserAuthenticcationTypeEnum;
import com.prd.model.LoginUser;
import com.prd.model.UserDO;
import com.prd.service.FileService;
import com.prd.service.NotifyService;
import com.prd.service.UserService;
import com.prd.util.CheckUtil;
import com.prd.util.CommonUtil;
import com.prd.util.HttpUtils;
import com.prd.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author lizhaoyi
 * @date 2023/11/20 13:59
 * Description:
 */

@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {

    @Autowired
    private UserService service;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private FileService fileService;


    /**
     * 验证码10分钟有效
     */
    private static final int CODE_EXPIRED = 60 * 1000 * 10;


    /**
     * 发送手机号验证码
     * @param to
     */
    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, String to) {

        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY,sendCodeEnum.name(),to);

        String cacheValue = redisTemplate.opsForValue().get(cacheKey);

        //如果不为空，则判断是否60秒内重复发送
        if(StringUtils.isNotBlank(cacheValue)){
            long ttl = Long.parseLong(cacheValue.split("_")[1]);
            //当前时间戳-验证码发送时间戳，如果小于60秒，则不给重复发送
            if(CommonUtil.getCurrentTimestamp() - ttl < 1000*60){
                log.info("重复发送验证码,时间间隔:{} 秒",(CommonUtil.getCurrentTimestamp()-ttl)/1000);
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }
        //存入redis缓存中
        String code = CommonUtil.getRandomCode(4);
        String value = code+"_"+CommonUtil.getCurrentTimestamp();
        redisTemplate.opsForValue().set(cacheKey,value,CODE_EXPIRED, TimeUnit.MILLISECONDS);

        if(CheckUtil.isPhone(to)){
            //发送短信 TODO

            return JsonData.buildSuccess(code);
        }

        return JsonData.buildResult(BizCodeEnum.CODE_TO_ERROR);

    }

    /**
     * 实名认证
     * @param name
     * @param idCardNum
     * @param idCardFaceImg
     * @param idCardBackImg
     * @return
     */
    @Override
    public JsonData authenticate(String name, String idCardNum,String idCardFaceImg,String idCardBackImg) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        //调用第三方接口 TODO

        //更新数据
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(loginUser,userDO);
        userDO.setIsReal(UserAuthenticcationTypeEnum.TRUE.getCode());
        userDO.setName(name);
        if (StringUtils.isNotEmpty(idCardFaceImg)) {
            userDO.setIdCardFaceImg(idCardFaceImg);
        }
        if (StringUtils.isNotEmpty(idCardBackImg)) {
            userDO.setIdCardFaceImg(idCardBackImg);
        }
        if (service.updateById(userDO)) {
            return JsonData.buildSuccess();
        }

        return JsonData.buildError("实名认证操作异常");
    }

    private boolean authenticate() {
        String host = "https://zid.market.alicloudapi.com";
        String path = "/idcheck/Post";
        String method = "POST";
        String appcode = "prd";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("cardNo", "370323198308203017");
        bodys.put("realName", "任洪宾");

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            int httpCode= response.getStatusLine().getStatusCode();
            if (httpCode == 200) {
                System.out.println("正常请求计费(其他均不计费)");
                System.out.println("获取返回的json：");
                System.out.println(EntityUtils.toString(response.getEntity()));
                return true;

            } else {
                // Map<String, List<String>> map = response.getAllHeaders().map();
                //String error = map.get("X-Ca-Error-Message").get(0);
                String error = response.getFirstHeader("X-Ca-Error-Message").getValue();
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    System.out.println("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    System.out.println("请求的 Method、Path 或者环境错误");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    System.out.println("参数错误");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    System.out.println("服务未被授权（或URL和Path不正确）");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    System.out.println("套餐包次数用完 ");
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    System.out.println(error);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    private void sentMessage(String code, String to) {
        //短信api调用地址
        String host = "https://dfsns.market.alicloudapi.com";
        //请求路径
        String path = "/data/send_sms";
        //请求方式
        String method = "POST";
        //appcode：自己的AppCode，可以在自己的控制台找到，是一串32位的字符串
        String appcode = "14xfa0523x3s2fe8ep0u54te14c2w36ad";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        //这里是要发送给用户的验证码，我们使用了随机数进行生成
        bodys.put("content", "code:"+code);
        //这里是接受短信的手机号码，我们在实际开发时这里就不能写死了
        bodys.put("phone_number", to);
        //这里是发送短信的模板ID：代表整体短信文案模板
        bodys.put("template_id", "TPL_0000");
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
